
<template>
  <div id="oder-list" class="app-container calendar-list-container">
    <div class="filter-container">
      <el-form :inline="true" ref="ruleForm">
        <el-form-item>
          <el-button
            icon="el-icon-circle-plus-outline"
            type="button"
            class="el-button el-button--primary"
            @click="
              dialogFormVisible = true;
              diaTitle = '添加管理员';
              isCreate = 'true';
            "
          >
            添加管理员</el-button
          >
        </el-form-item>


      </el-form>
    </div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      v-loading="loading"
      element-loading-text="给我一点时间"
      style="width: 100%"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
    >
      <el-table-column type="index" label="序号"> </el-table-column>
      <el-table-column prop="userName" label="管理员名称"></el-table-column>
      <el-table-column prop="userAcount" label="管理员账号"> </el-table-column>
      <el-table-column prop="managerType" label="管理员类型"> </el-table-column>
      <el-table-column prop="managerId" label="管理员ID"> </el-table-column>
      <el-table-column prop="groupId" label="所属群组"> </el-table-column>
      <el-table-column prop="ctime" label="创建时间"> </el-table-column>
      <el-table-column prop="isFlag" label="是否使用">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isFlag"
            active-color="#13ce66"
            inactive-color="#ccc"
            :active-value="1"
            :inactive-value="0"
            @change="editManagerStatus(scope.row.managerId)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="operate" align="center" label="操作" width="400">
        <template slot-scope="scope">
          <div class="fx" style="display: flex">
            <el-button
              @click="editManager(scope.row)"
              type="button"
              icon="el-icon-setting"
              class="el-button el-button--primary"
              >修改</el-button
            >
            <el-button
              type="button"
              class="el-button el-button--primary"
              @click="getRole(scope.row.managerId)"
              >分配角色</el-button
            >
            <el-button
              type="button"
              icon="el-icon-delete"
              class="el-button el-button--danger"
              @click="deleteManager(scope.row.managerId)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- //新增 修改 -->
    <el-dialog
      :title="diaTitle"
      :visible.sync="dialogFormVisible"
      @close="closeDialog"
      width="40%"
    >
      <el-form :model="createForm" ref="createForm" :rules="createRules">
        <el-form-item
          prop="userName"
          label="管理员名称"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="createForm.userName"
            auto-complete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="editShow"
          prop="userAcount"
          label="管理员账号"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="createForm.userAcount"
            auto-complete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="editShow"
          prop="passWord"
          label="管理员密码"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="createForm.passWord"
            auto-complete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          v-if="isCreate == 'true'"
          type="primary"
          @click="submitForm('createForm')"
          >创建</el-button
        >
        <el-button v-else type="primary" @click="edit('createForm')"
          >修改</el-button
        >
      </div>
    </el-dialog>
    <!-- 角色分配 -->
    <el-dialog
      title="角色分配"
      :visible.sync="roleShow"
      @close="closeDialog"
      width="50%"
      v-loading="loading"
    >
      <el-form :model="roleForm">
        <el-form-item
          prop="name"
          label="角色节点"
          :label-width="formLabelWidth"
        >
          <div style="margin-right: 20px">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
          </div>
          <el-checkbox-group
            v-model="roleCheck"
            @change="handleCheckedRoleChange"
          >
            <el-checkbox
              v-for="(item, index) in roleData"
              :key="index"
              :value="item.id"
              :label="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="roleAllocation()">分配角色</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getManagers,
  createManager,
  editManager,
  managerStatus,
  deleteManager,
  assignRole,
  getManagerRole,
} from "@/api/managerList";
import { AllRole } from "@/api/role";
export default {
  data() {
    return {
      roleCheck: [],
      isIndeterminate: false,
      checkAll: false,
      roleData: [],
      roleForm: {
        //角色
        name: "",
      },
      managerId: "",
      roleIds: [],
      roleShow: false,
      roleProps: {
        children: "children",
        label: "title",
      },
      editShow: true,
      isFlag: 1,
      loading: false,
      total: 0,

      editID: "",
      isCreate: "",
      diaTitle: "",
      dialogFormVisible: false,
      formLabelWidth: "140px",
      tableData: [],
      createForm: {
        userAcount: "",
        userName: "",
        passWord: "",
      },
      createRules: {
        userAcount: [
          { required: true, message: "请输入账号", trigger: "change" },
        ],
        passWord: [
          { required: true, message: "请输入密码", trigger: "change" },
        ],
        userName: [
          { required: true, message: "请输入用户名", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    handleCheckAllChange(val) {
      const all = this.roleData.map((item) => {
        return item.id;
      });
      this.roleCheck = val ? all : [];
      this.isIndeterminate = false;
      // this.roleIds = this.roleCheck;
    },
    handleCheckedRoleChange(value) {
      this.roleIds = value;
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.roleData.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.roleData.length;
    },
    // 提交分配角色
    async roleAllocation() {
      let query = {
        managerId: this.managerId,
        roleIds: this.roleIds.join(","),
      };
      let res = await assignRole(query);
      if (res.code == 1) {
        this.roleShow = false;
        this.getAllManagers();
        this.$message.success("分配角色成功");
      } else {
        this.roleShow = false;
        this.getAllManagers();
        this.$message.error("分配角色失败");
      }
    },
    // 获取角色信息
    async getRole(managerId) {
      this.roleData = [];
      let roleTree = await AllRole();
      let hasRole = await getManagerRole(managerId);
      // this.roleCheck = [];
      if (roleTree.code == 1) {
        this.roleData = roleTree.data;
        if (hasRole.data) {
          roleTree.data.map((item) => {
            hasRole.data.map((item2) => {
              if (item.id == item2.id) {
                this.roleCheck.push(item2.id);
              }
            });
          });
        }
        if (this.roleCheck.length > 0) {
          this.roleIds = this.roleCheck;
        }
        this.managerId = managerId;
        this.roleShow = true;
      }
    },

    // 状态修改
    async editManagerStatus(id) {
      let status = this.isFlag;
      let res = await managerStatus(id, status);
      if (res.code == 1) {
        this.$message.success("状态变更成功");
      } else {
        this.$message.error("状态变更失败");
        return;
      }
    },
    clear() {
      this.getAllManagers();
    },
    //   删除管理员
    deleteManager(id) {
      this.$confirm("确定删除管理员", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await deleteManager(id);
          if (res.code == 1) {
            this.$message.success("删除管理员成功");
            this.getAllManagers();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    sizeChange(val) {
      this.pageSize = val;
      this.searchMenu();
    },
    currentChange(val) {
      this.pageNum = val;
      this.searchMenu();
    },
    // 修改管理员
    editManager(row) {
      this.diaTitle = "管理员修改";
      this.editShow = false;

      this.createForm = {
        userAcount: row.userAccount,
        userName: row.userName,
        passWord: row.passWord,
      };
      this.editID = row.managerId;
      this.dialogFormVisible = true;
    },
    // 管理员修改提交
    async edit(createForm) {
      this.$refs[createForm].validate(async (valid) => {
        //开启校验
        if (valid) {
          this.createForm.userName;
          let userName = this.createForm.userName.toString();
          let res = await editManager(this.editID, userName);
          if (res.code == 1) {
            this.$message.success("管理员修改成功");
            this.getAllManagers();
            this.dialogFormVisible = false;
            this.createForm = {
              userAcount: "",
              userName: "",
              passWord: "",
            };
          } else {
            this.$message.error("管理员修改失败");
            this.dialogFormVisible = false;
            this.createForm = {
              userAcount: "",
              userName: "",
              passWord: "",
            };
          }
        } else {
          //校验不通过
          return false;
        }
      });
    },
    // 对话框关闭
    closeDialog() {
      if (this.$refs.createForm) {
        this.$refs.createForm.resetFields();
      }
      this.isCreate = "";
      this.createForm = {
        userAcount: "",
        userName: "",
        passWord: "",
      };
      this.editShow = true;
      this.roleCheck = [];
    },

    // 获取所有后台管理员
    async getAllManagers() {
      this.loading = true;
      let res = await getManagers();
      if (res.code == 1) {
        this.tableData = res.data;
      }
      this.loading = false;
    },

    // 添加管理员
    async createManager() {
      const res = await createManager(this.createForm);
      if (res.code == 1) {
        this.$message.success("管理员创建成功");
        this.getAllManagers();
        this.dialogFormVisible = false;
        this.createForm = {
          userAcount: "",
          userName: "",
          passWord: "",
        };
      } else {
        this.$message.error("管理员创建失败");
        this.dialogFormVisible = false;
        this.createForm = {
          userAcount: "",
          userName: "",
          passWord: "",
        };
      }
    },

    // 创建提交
    submitForm(createForm) {
      this.$refs[createForm].validate((valid) => {
        //开启校验
        if (valid) {
          // 如果校验通过，请求接口，允许提交表单
          this.createManager();
        } else {
          //校验不通过
          return false;
        }
      });
    },
  },
  computed: {},
  mounted() {},
  created() {
    this.getAllManagers();
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-tree-node,
/deep/ .custom-tree-node {
  margin-bottom: 10px;
}
label {
  font-weight: 700;
}
/deep/ .custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
}
/deep/ .el-dialog__footer {
  text-align: center;
}
</style>
